package com.fingard.dsp.bank.directbank.fngrd01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IContract;
import com.fingard.dsp.bank.reqrespobj.contract.*;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;


public class FnGrd01Contract extends FnGrd01Base implements IContract {
    /**
     * 签约
     */
    @Override
    public RetAtsContract contract(ReqContract p_req) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;
        try {
            FnGrd01Header bankHeader = new FnGrd01Header();
            bankHeader.CorpBankCode = getBankConfig().getMapValueByKey("corBankCodeMapping", p_req.contractDetail.recAct);
            if (StringHelper.isNullOrEmpty(bankHeader.CorpBankCode)) {
                WriteBankLogLn2("CorpBankCode为空，请配置corBankCodeMapping映射");
            }
            bankHeader.TransSeqID = getQryTransID();
            if ("01".equals(p_req.contractDetail.step)) {
                bankHeader.CommandCode = "311A2";
            } else if ("02".equals(p_req.contractDetail.step)) {
                bankHeader.CommandCode = "311D2";
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("SignReq");
            xmlWriter.writeElementString("Flag", "0");/* 0:签约 1:解约*/
            xmlWriter.writeElementString("CorpAct", p_req.contractDetail.recAct);/* 企业方账号 */

            String[] authCodeSp = p_req.contractDetail.authCode.split("__");
            String protocolCode = authCodeSp[0];


            /* 协议号 	*/
            xmlWriter.writeElementString("ProtocolCode", protocolCode);
            /*签约适用指令
            111G1 单笔代收
            111B1 单笔部分留底扣款????	*/
            xmlWriter.writeElementString("ForCommandCode", "111G1");
            xmlWriter.writeElementString("CustAct", p_req.contractDetail.payAct);
            xmlWriter.writeElementString("CustName", p_req.contractDetail.payName);
            xmlWriter.writeElementString("CertType", convertCertTypeToBank(p_req.contractDetail.certType));
            xmlWriter.writeElementString("CertNum", p_req.contractDetail.certNum);
            xmlWriter.writeElementString("Mobile", p_req.contractDetail.cellPhone);
            //单笔限额
            String singleLimit = p_req.contractDetail.singleLimit;
            if (StringHelper.isNullOrEmpty(singleLimit)) {
                singleLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "singleLimit");
            }
            //合约结束日期
            String deadLine = p_req.contractDetail.deadLine;
            if (StringHelper.isNullOrEmpty(deadLine)) {
                deadLine = getBankConfig().getMapValueByKey("contractKeyMapping", "deadLine");
            }

            xmlWriter.writeElementString("LimitAmount", singleLimit);
            xmlWriter.writeElementString("DealStartDate", Format.Date8Format.format(new Date()));
            xmlWriter.writeElementString("DealEndDate", deadLine);
            //回复短信的验证方式回复短信验证码方式
            //1 短信回复 默认
            //2 接口发送
            //3 H5,目前只支持招行
            xmlWriter.writeElementString("ReplySmsType", getBankConfig().getMapValueByKey("signModeBankMapping", p_req.contractDetail.payBankCode));

            if ("01".equals(p_req.contractDetail.step)) {
                xmlWriter.writeElementString("CertCode", "");
            } else {
                xmlWriter.writeElementString("CertCode", p_req.contractDetail.smsCode);
            }

            //日累计限额
            String dayAmtLimit = p_req.contractDetail.dayAmtLimit;
            if (StringHelper.isNullOrEmpty(dayAmtLimit)) {
                dayAmtLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "dayAmtLimit");
            }
            //月累计限额
            String monthAmtLimit = p_req.contractDetail.monthAmtLimit;
            if (StringHelper.isNullOrEmpty(monthAmtLimit)) {
                monthAmtLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "monthAmtLimit");
            }
            xmlWriter.writeElementString("DayUpAmount", dayAmtLimit);
            xmlWriter.writeElementString("MonthUpAmount", monthAmtLimit);

            //扣款周期
            if ("1".equals(p_req.contractDetail.periodLimit)) {
                xmlWriter.writeElementString("Period", "D");
            } else if ("2".equals(p_req.contractDetail.periodLimit)) {
                xmlWriter.writeElementString("Period", "M");
            } else if ("3".equals(p_req.contractDetail.periodLimit)) {
                xmlWriter.writeElementString("Period", "Y");
            } else {
                xmlWriter.writeElementString("Period", "D");
            }
            if (StringHelper.hasAnyChar(p_req.contractDetail.insuPolicyNum)) {
                xmlWriter.writeElementString("PolicyNumber", p_req.contractDetail.insuPolicyNum);
            } else {
                xmlWriter.writeElementString("PolicyNumber", p_req.contractDetail.sourceNoteCode);
            }
            xmlWriter.writeElementString("SignBusType", "D30");
            String jumpUrl = p_req.contractDetail.jumpUrl;
            if (StringHelper.isNullOrEmpty(jumpUrl)) {
                jumpUrl = getBankConfig().getValueAsString("jumpUrl");
            }
            xmlWriter.writeElementString("JumpUrl", jumpUrl);
            xmlWriter.writeEndDocument();

            String[] tmpRetStr = sendToBank(xmlWriter.toXmlString());
            if (tmpRetStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/Root/Head/RespCode");
                    String tmpRetMsg = tmpBkReader.getFirstText("/Root/Head/RespInfo");
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Root/SignResp/ResultInfo");
                    String tmpState = tmpBkReader.getFirstText("/Root/SignResp/ResultState");
                    /**融汇渠道回复短信验证码方式 1短信回复 默认    2接口发送*/
                    String retReplySmsType = tmpBkReader.getFirstText("/Root/SignResp/ReplySmsType");
                    if ("1".equals(retReplySmsType)) {
                        tmpRetDetail.signConfirmType = "3";//ats 3短信回复（异步通知）即上行短信
                    } else if ("2".equals(retReplySmsType)) {
                        tmpRetDetail.signConfirmType = "2";//ats 2短信验证码
                    }
                    String tmpErrCode = "";
                    String authCode = "";

                    if ("01".equals(p_req.contractDetail.step)) {
                        if ("4".equals(tmpState)) {
                            tmpErrCode = "I4001";
                            authCode = tmpBkReader.getFirstText("/Root/SignResp/ProtocolCode");
                            tmpRetDetail.authCode = authCode;
                            tmpRetDetail.newAuthCode = authCode + "__" + tmpBkReader.getFirstText("/Root/SignResp/AgreementNo");
                        } else if ("3".equals(tmpState)) {
                            tmpErrCode = "E8001";
                        } else {
                            tmpRetDetail.respCode = "-1";
                        }
                        tmpRetDetail.signUrl = tmpBkReader.getFirstText("/Root/SignResp/SignUrl");
                    } else {
                        if ("2".equals(tmpState)) {
                            // 签约状态: 2：签约成功，3：签约失败
                            tmpRetDetail.signState = ContractState.SUCCESS;
                            tmpErrCode = "S0000";
                            //<ProtocolCode>140003</ProtocolCode>
                            //<AgreementNo>010AD091011911146384987</AgreementNo>
                            authCode = tmpBkReader.getFirstText("/Root/SignResp/ProtocolCode");
                            String agreementNo = tmpBkReader.getFirstText("/Root/SignResp/AgreementNo");/* 代收协议编号 */
                            tmpRetDetail.authCode = authCode;
                            tmpRetDetail.newAuthCode = authCode + "__" + agreementNo;
                        } else if ("3".equals(tmpState)) {
                            tmpRetDetail.signState = ContractState.FAIL;
                            tmpErrCode = "E8001";
                        } else {
                            tmpRetDetail.respCode = "-1";
                        }
                    }
                    tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", tmpErrCode);
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpRetStr[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsContract upContract(ReqContract p_req) throws Exception {
        return null;
    }

    /**
     * 签约交易查证
     */
    @Override
    public RetAtsContract qryContract(ReqContract p_reqQry) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_reqQry.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;
        try {
            FnGrd01Header bankHeader = new FnGrd01Header();
            bankHeader.CorpBankCode = getBankConfig().getMapValueByKey("corBankCodeMapping", p_reqQry.contractDetail.recAct);
            if (StringHelper.isNullOrEmpty(bankHeader.CorpBankCode)) {
                WriteBankLogLn2("CorpBankCode为空，请配置corBankCodeMapping映射");
            }
            bankHeader.CommandCode = "211A2";
            bankHeader.TransSeqID = getQryTransID();
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("SignQueryReq");
            xmlWriter.writeElementString("Flag", "0");/* 0:签约 1:解约*/
            xmlWriter.writeElementString("CorpAct", p_reqQry.contractDetail.recAct);
            String[] authCodeSp = p_reqQry.contractDetail.authCode.split("__");
            String protocolCode = authCodeSp[0];
            if ("".equals(protocolCode)) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.signConfirmType = "2";
                tmpRetDetail.signState = ContractState.UNSIGNED;
                tmpRetDetail.respInfo = "ProtocolCode为空，未签约";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            xmlWriter.writeElementString("ProtocolCode", protocolCode);/* 协议号 	*/
            xmlWriter.writeElementString("CustAct", p_reqQry.contractDetail.payAct);
            xmlWriter.writeElementString("ForCommandCode", "111G1");
            xmlWriter.writeEndDocument();
            String[] tmpRetStr = sendToBank(xmlWriter.toXmlString());
            if (tmpRetStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Root/Head/RespInfo");

                    String tmpState = tmpBkReader.getFirstText("/Root/SignQueryResp/ResultState");
                    if ("2".equals(tmpState)) {
                        // 签约状态:2：签约成功，3：签约失败（具体错误原因）
                        tmpRetDetail.signState = ContractState.SUCCESS;
                        String authCode = tmpBkReader.getFirstText("/Root/SignQueryResp/ProtocolCode");
                        String agreementNo = tmpBkReader.getFirstText("/Root/SignQueryResp/AgreementNo");/* 代收协议编号 */
                        tmpRetDetail.authCode = authCode;
                        tmpRetDetail.newAuthCode = authCode + "__" + agreementNo;
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Root/SignQueryResp/ResultInfo");
                    } else if ("3".equals(tmpState)) {
                        tmpRetDetail.signState = ContractState.FAIL;
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Root/SignQueryResp/ResultInfo");
                    } else if ("4".equals(tmpState)) {
                        tmpRetDetail.signState = ContractState.SIGNING;
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Root/SignQueryResp/ResultInfo");
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Root/Head/RespInfo");
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpRetStr[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsQryBatContract qryBatContract(ReqQryBatContract p_reqQry) throws Exception {
        return null;
    }

}

